package com.sailfish.springbootdemo.configs;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.swing.plaf.synth.Region;

@Configuration
public class S3Config {

    @Value("${personal.config.amazon-s3.access-key}")
    private String accessKey;

    @Value("${personal.config.amazon-s3.secret-key}")
    private String secretKey;

    @Value("${personal.config.amazon-s3.url}")
    private String url;

    @Value("${personal.config.amazon-s3.file-bucket}")
    private String fileBucket;

    private String region = "default";

    @Bean
    public AmazonS3 amazonS3() {
        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(url, region);

        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
        AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setProtocol(Protocol.HTTPS);

        AmazonS3 s3Client = AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfiguration)
                .withClientConfiguration(clientConfiguration)
                .withCredentials(awsCredentialsProvider)
                .disableChunkedEncoding()
                .withPathStyleAccessEnabled(true)
                .withForceGlobalBucketAccessEnabled(true)
                .build();

        createBucket(s3Client);
        return s3Client;
    }

    public void createBucket(AmazonS3 s3Client) {
        try {
            if (s3Client.doesBucketExistV2((fileBucket))) {
                System.out.println(String.format("Bucket %s already exists.", fileBucket));
            } else {
                try {
                    s3Client.createBucket(fileBucket);
                } catch (Exception e) {
                    System.out.println("create s3 bucket error:" + e.getMessage());
                }
            }
        } catch (Exception e) {
            System.out.println("doesBucketExistV2 s3 bucket error:" + e.getMessage());
        }

    }
}
